package com.xdy.secret.algorithm;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;

/**
 * @Author: XDY.
 * @Email: 2280944114@qq.com
 * @CreateTime: 2023-09-06  00:34
 * @Description: 数字签名
 * @Version: 1.0
 */
public class SignatureDemo {
    public static void main(String[] args) throws Exception {
        //原文
        String input = "许琳康";
        PublicKey publicKey = RSADemo.getPublicKey("a.pub", "RSA");
        PrivateKey privateKey = RSADemo.getPrivateKey("a.pri", "RSA");
        //获取数字签名
        String signatureData = getSignature(input, "sha256withrsa", privateKey);
        System.out.println("signatureData = " + signatureData);
        //校验签名
//        input = "许琳康1";//修改原文之后校验签名失败
        boolean b = verifySignature(input, "sha256withrsa", publicKey, signatureData);
        System.out.println("b = " + b);
    }

    /**
     * 校验签名
     * @param input 原文数据
     * @param algorithm 非对称加密算法
     * @param publicKey 加密公钥
     * @param signatureData 签名摘要
     * @return
     * @throws Exception
     */
    private static boolean verifySignature(String input, String algorithm, PublicKey publicKey, String signatureData) throws Exception {
        //获取签名对象
        Signature signature = Signature.getInstance(algorithm);
        //初始化校验
        signature.initVerify(publicKey);
        //传入原文
        signature.update(input.getBytes());
        //校验数据
        return signature.verify(Base64.decode(signatureData));
    }

    /**
     * 生成数字签名
     * @param input 原文
     * @param algorithm 非对称加密算法
     * @param privateKey 加密私钥
     * @return
     */
    public static String getSignature(String input, String algorithm, PrivateKey privateKey) throws Exception{
        //获取签名对象
        Signature signature = Signature.getInstance(algorithm);
        //初始化签名
        signature.initSign(privateKey);
        //传入原文
        signature.update(input.getBytes());
        //开始签名
        byte[] sign = signature.sign();
        //使用base64进行编码
        return Base64.encode(sign);
    }
}
